package com.huayi.order.controller;

import com.huayi.order.entity.ErpSalesOrderDetailVo;
import com.huayi.order.entity.ErpSalesOrderItemEntity;
import com.huayi.order.enums.EnumErpOrderStatus;
import com.huayi.order.enums.EnumSalesOrderPayStatus;
import com.huayi.order.service.ErpSalesOrderService;
import com.huayi.order.utils.DateUtil;
import com.huayi.order.utils.OrderNumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/order")
public class OrderEditController {
    @Autowired
    private ErpSalesOrderService salesOrderService;

    /**
     * 系统下单
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String login(Model model, @RequestParam Long id, HttpServletRequest request) {

        ErpSalesOrderDetailVo orderDetail = salesOrderService.getDetailById(id);
        orderDetail.setAddress(orderDetail.getAddress().replace(orderDetail.getProvince()+orderDetail.getCity()+orderDetail.getArea(),""));
        model.addAttribute("order", orderDetail);


        model.addAttribute("menuId", "order_list");
        return "order_edit";

    }


    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String postSystemOrder(Model model, HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object userId = request.getSession().getAttribute("userId");
        //return "/permission_denied";
        model.addAttribute("menuId", "order_list");
        /***商品信息****/

        String[] goodsArr = request.getParameterValues("goods");//商品
        String[] quantityArr = request.getParameterValues("quantity");//数量组合
        String[] priceArr = request.getParameterValues("price");//商品价格

        //收件人信息
        String contactMobile = request.getParameter("contactMobile");
        String contactPerson = request.getParameter("contactPerson");
        String area = request.getParameter("area");
        String address = request.getParameter("address");
        String saleType = request.getParameter("saleType");
        String shippingFee= StringUtils.isEmpty(request.getParameter("shippingFee")) ? "0" :request.getParameter("shippingFee");
        String sellerMemo = request.getParameter("sellerMemo");
        Integer payStatus = Integer.parseInt(request.getParameter("payStatus"));
        Integer payMethod = 0;
        if(StringUtils.isEmpty(request.getParameter("payMethod"))==false){
            payMethod = Integer.parseInt(request.getParameter("payMethod"));
        }

        String[] areaNameArray = area.split(" ");

        String provinceName = "";
        if (areaNameArray.length > 0) provinceName = areaNameArray[0];
        String cityName = "";
        if (areaNameArray.length > 1) cityName = areaNameArray[1];
        String districtName = "";
        if (areaNameArray.length > 2) districtName = areaNameArray[2];

        //下单人信息
        ErpSalesOrderDetailVo salesOrder= new ErpSalesOrderDetailVo();

        List<ErpSalesOrderItemEntity> items=new ArrayList<>();
        Long goodsCount=0L;//商品数量

        double goodsTotalAmount = 0;//商品总价

        for (int i = 0,n=goodsArr.length;i<n;i++) {
            if(StringUtils.isEmpty(goodsArr[i]))continue;

            ErpSalesOrderItemEntity item= new ErpSalesOrderItemEntity();

            BigDecimal price = new BigDecimal(priceArr[i]);
            Integer count =Integer.parseInt(quantityArr[i]);
            String goods = goodsArr[i];
            item.setGoodsTitle(goods);
            //if(count.intValue()>spec.getCurrentQty())continue;
            goodsCount+=count;

            goodsTotalAmount +=  price.doubleValue() * count;
            item.setItemAmount(BigDecimal.valueOf(price.doubleValue() * count));
            item.setQuantity(count);
            item.setPrice(price);
            items.add(item);
        }

        salesOrder.setId(Long.parseLong(request.getParameter("id")));
        salesOrder.setGoodsTotalAmount(new BigDecimal(goodsTotalAmount));
        salesOrder.setContactMobile(contactMobile);
        salesOrder.setContactPerson(contactPerson);
        salesOrder.setProvince(provinceName);
        salesOrder.setCity(cityName);
        salesOrder.setArea(districtName);
        salesOrder.setAddress(provinceName+cityName+districtName+address);
        salesOrder.setItems(items);
        salesOrder.setSaleType(Integer.parseInt(saleType));
        salesOrder.setShippingFee(new BigDecimal(0));

//        salesOrder.setOrderNum();
        salesOrder.setTotalAmount(new BigDecimal(goodsTotalAmount).add(new BigDecimal(shippingFee)));


        if(payStatus.intValue() == 0){
            //未付款订单
            salesOrder.setStatus(EnumErpOrderStatus.WaitAudit.getIndex());
            salesOrder.setPayAmount(new BigDecimal(0));//付款金额
            salesOrder.setPayTime(0L);
            salesOrder.setPayStatus(EnumSalesOrderPayStatus.NotPay.getIndex());
        }else if(payStatus.intValue() == 2){
            //已付款订单
            salesOrder.setStatus(EnumErpOrderStatus.WaitSend.getIndex());
            salesOrder.setPayAmount(new BigDecimal(goodsTotalAmount).add(new BigDecimal(shippingFee)));//付款金额
            salesOrder.setPayTime(System.currentTimeMillis() / 1000 );
            salesOrder.setPayStatus(EnumSalesOrderPayStatus.CompletePay.getIndex());
        }

        salesOrder.setPayMethod(payMethod);


        salesOrder.setOrderDate(DateUtil.getCurrentDate());
        salesOrder.setShippingFee(new BigDecimal(shippingFee));
        salesOrder.setSellerMemo(sellerMemo);
        salesOrder.setCreateOn(System.currentTimeMillis() / 1000);

        if(goodsCount>0) salesOrderService.editSalesOrder(salesOrder);
        return "redirect:/order/list";

    }

}
